package com.xgo.channel.tool;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Channel init Tool
 * Created by ljb on 2016/2/25.
 */
public class ChannelTool {
    /**
     * Init
     *
     * @param context
     * @param startWord ：startWord_channelName
     *
     * @return ChannelName 渠道名
     */
    public static String init(Context context, String startWord) {
        String channelFileName = getChannelFileName(context, startWord);
        return getChannelName(context, channelFileName);
    }

    /**
     * 更新配置文件
     */
    private static String getChannelName(Context context, String channelFileName) {
        Log.d("xgo", "channelFileName::" + channelFileName);

        String[] datas = channelFileName.split("_");
        if (datas.length >= 2) {

            return channelFileName.substring(datas[0].length() + 1);
        }

        return "default";
    }

    /**
     * 获取渠道文件名
     */
    private static String getChannelFileName(Context context, String startWord) {
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                Log.i("xgo", "entryName::" + entryName);
                if (entryName.contains(startWord)) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

}
